import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
// import iView from 'iview';
import ViewUI from 'view-design'
import { newagentConfig } from "@/libs/wwsignname";
import { Routers } from './routers'
import baseRouter from '@/router/routers.js'
import { asyncRoutes } from '@/router/asyncRoutes.js'
import {
    setToken,
    getToken,
    removeToken,
    canTurnTo,
    setTitle
} from '@/libs/util'
import config from '@/config'
import service from '@/libs/service.js'
import routeAddress from './routeAddress'
import { mapActions } from "vuex";
// import userManagement from '../view/userManagement/userManagement.vue'

// const routeAddress = {
//   userManagement
// }
// 路由暂时这样 后期优化


if (getToken() && !localStorage.routers) {
    removeToken()
}

var getRouter
const { homeName } = config
// console.log('woshi0', localStorage.getItem('routers'));
const InitialRoutes = service.getObjArr(routes, 1, routeAddress)
console.log('拿到的第一份路由', InitialRoutes);
Vue.use(Router)

// 解决导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push



Router.prototype.push = function push (location) {
    return originalPush.call(this, location).catch(err => err)
}
console.log('无敌滴', getRouter);
const router = new Router({
    routes: routes,
    Routers,
    mode: 'hash'
})

const LOGIN_PAGE_NAME = 'login'
const whiteList = ['/', 'login', 'register', 'findpassword']  // 白名单 不跳转登录页面
const turnTo = (to, access, next) => {
    if (canTurnTo(to.name, access, InitialRoutes)) {
        if (to.name === homeName) {
            next({ replace: true, name: homeName })
        } else {
            next()
        }
        // 有权限，可访问
    } else {
        next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
    }
}


router.beforeEach(async (to, from, next) => {
    if (!store.state.user.routerList) {
        const hebing = true
        await store.dispatch('getTbMenuQueryData', hebing)
        next({ ...to, replace: true })
      } else {
        next()
    }
    if (!getRouter) {
        
        // 登录到首页
        newagentConfig()
        // 不加这个判断，路由会陷入死循环
        if (!localStorage.routers || JSON.parse(localStorage.routers).length < 1) {
            routingRules(to, from, next)
        } else {
            // 从localStorage拿到了路由
            
            getRouter = service.getObjArr(routes, 2, routeAddress) // 拿到路由
            // router.addRoute(getRouter)
            console.log('拿', getRouter);
            // store.user.jj = getRouter
            console.log('拿到路由', getRouter);
            routerGo(to, from, next)
        }
    } else {
        const token = getToken()
        if (!token && !whiteList.includes(to.name)) {
            // 未登录且要跳转的页面不是登录页
            next({
                name: LOGIN_PAGE_NAME
            })
        } else if (!token && to.name === LOGIN_PAGE_NAME) {
            {
                // 未登陆且要跳转的页面是登录页
                next() // 跳转
            }
        } else if (token && to.name === LOGIN_PAGE_NAME) {
            // 已登录且要跳转的页面是登录页
            if (window.location.href.split("auth_code=")[1] != undefined) {
                if (window.location.href.indexOf("&appid=") != -1) {
                    // 企业微信扫码登录
                    next({
                        name: homeName // 跳转到homeName页
                    })
                } else if (window.location.href.indexOf("&state=") != -1) {
                    // 企业微信授权 注册? 并登录
                    next({
                        name: homeName // 跳转到homeName页
                    })
                } else if (window.location.href.split("auth_code=")[1].split("#/")[1].split('=')[1] == '1') {
                    removeToken();
                    localStorage.clear();
                    next({
                        name: 'login'
                    })
                } else {
                    next({
                        name: homeName // 跳转到homeName页
                    })
                }
            } else {
                next({
                    name: homeName // 跳转到homeName页
                })
            }
        } else if (token && to.name === 'home') {
            next()
        }
        else {
            // 已登录每次跳路由都会触发
            
            next()
        }
    }
})
function routerGo (to, from, next) {
    // 添加路由
    console.log('添加到动态路由的路由', getRouter);
    console.log('Router添加前', router.addRoute);
    router.addRoutes(getRouter)
    console.log('Router添加后', router);
    routingRules(to, from, next)
}

const routingRules = (to, from, next) => {
    ViewUI.LoadingBar.start()
    const token = getToken()
    if (!token && !whiteList.includes(to.name)) {
        next({
            name: LOGIN_PAGE_NAME // 进登录
        })
    } else if (token && to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        if (window.location.href.split("auth_code=")[1] != undefined) {
            if (window.location.href.indexOf("&appid=") != -1) {
                // 企业微信扫码登录
                next({
                    name: homeName // 跳转到homeName页
                })
            } else if (window.location.href.indexOf("&state=") != -1) {
                // 企业微信授权 注册? 并登录
                next({
                    name: homeName // 跳转到homeName页
                })
            } else if (window.location.href.split("auth_code=")[1].split("#/")[1].split('=')[1] == '1') {
                removeToken();
                localStorage.clear();
                next({
                    name: 'login'
                })
            } else {
                next({
                    name: homeName // 跳转到homeName页
                })
            }
        } else {
            next({
                name: homeName // 跳转到homeName页
            })
        }
    } else {
        if (store.state.user.hasGetInfo) {
            turnTo(to, store.state.user.access, next)
        } else {
            store
                .dispatch('getUserInfo')
                .then(user => {
                    // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
                    turnTo(to, user.access, next)
                })
                .catch(() => {
                    setToken('')
                    next({
                        name: 'login'
                    })
                })
        }
    }
}
router.afterEach(to => {
    setTitle(to, router.app)
    ViewUI.LoadingBar.finish()
    window.scrollTo(0, 0)
})

export default router
